<?php

namespace catchAdmin\phone\controller;

use catcher\base\CatchController;
use catcher\base\CatchRequest;
use catcher\CatchResponse;
use catcher\CatchUpload;
use catcher\exceptions\FailedException;
use think\facade\Filesystem;

class Upload extends CatchController
{

    /**
     * pc上传
     */
    public function image1(CatchRequest $request, CatchUpload $upload): \think\response\Json
    {
        $images = $request->file();

        if (!$images) {
            return CatchResponse::fail('请选择图片上传');
        }

        $path = Filesystem::disk('public')
            ->putFile('/banner', $images['image']);

        return CatchResponse::success(
            request()->domain() . "/storage/" . $path
        );
    }


    /**
     * 多文件上传
     */
    public function imageMul(CatchUpload $upload): \think\response\Json
    {
        $images = request()->file();

//        if (!$images) {
//            throw new FailedException('请选择图片上传');
//        }
//
//        $path = '';

        $path_list = $upload
            ->checkImages($images)
            ->setPath('/aaa')
            ->multiUpload($images['image']);
        $list_2 = [];
        foreach ($path_list as $path) {
            $list_2[] = [
                'url' => $path,
            ];
        }

        return CatchResponse::success($list_2);
    }


    public function imageUrl()
    {
        // 验证文件
        try {
            $file = request()->file('file');
        } catch (\Exception $e) {
            return CatchResponse::fail('请上传图片');
        }

        $ext_arr = ['jpg', 'jpeg', 'gif', 'png'];
        if (!in_array($file->extension(), $ext_arr)) {
            return CatchResponse::fail('图片必须是的格式：' . implode(',', $ext_arr));
        }

        {
            $file_type = 1;
            if (!empty(request()->param('file_type'))) {
                $file_type = request()->param('file_type');
            }

            $path = $this->fileSave($file_type, $file);
        }

        try {
            // 返回访问 URL（根据实际域名调整）
            $url = '/storage/' . $path;

            if ($file->getSize() > 1024 * 1024 * 10) {
                exit(json_encode([
                    'code'    => 10005,
                    'message' => '上传失败，图片不能大于10M',
                ]));
            }

            // 图片大于2M压缩
            if ($file->getSize() > 1024 * 1024 * 1) {
                $url_arr = explode('.', $url);
                $url_to = $url_arr[0] . "_" . rand(100, 999) . "." . $file->extension();

                $url = imageThumb(substr($url, 1), substr($url_to, 1), $file->extension());
            }

            return json([
                'errno' => 0,
                'data'  => [
                    'url' => request()->domain() . $url,
                ],
            ]);
//            return CatchResponse::success($url);
        } catch (\Exception $e) {
            return CatchResponse::fail('上传失败');
        }
    }


    protected function fileSave($file_type, $file)
    {
        // 营业执照
        if ($file_type == 1) {
            // 存储图片（默认 public 磁盘）
            $path = Filesystem::disk('public')
                ->putFile('lience', $file);
            // 头像
        } elseif ($file_type == 2) {
            $path = Filesystem::disk('public')
                ->putFile('avatar', $file);
            // 新闻
        } elseif ($file_type == 3) {
            $path = Filesystem::disk('public')
                ->putFile('news', $file);
            // 需求
        } elseif ($file_type == 4) {
            $path = Filesystem::disk('public')
                ->putFile('need', $file);
            // 反馈
        } elseif ($file_type == 5) {
            $path = Filesystem::disk('public')
                ->putFile('feedback', $file);
            // 资质
        } elseif ($file_type == 6) {
            $path = Filesystem::disk('public')
                ->putFile('zi_zhi', $file);
            // 留言
        } elseif ($file_type == 7) {
            $path = Filesystem::disk('public')
                ->putFile('liu_yan', $file);
        } else {
            return CatchResponse::fail('参数异常');
        }

        return $path;
    }


    /**
     * 单图上传
     */
    public function image()
    {
        // 验证文件
        try {
            $file = request()->file('file');
        } catch (\Exception $e) {
            exit(json_encode([
                'code'    => 10005,
                'message' => '上传失败',
            ]));
        }

        $ext_arr = ['jpg', 'jpeg', 'gif', 'png'];
        if (!in_array($file->extension(), $ext_arr)) {
            exit(json_encode([
                'code'    => 10005,
                'message' => '图片必须是的格式：' . implode(',', $ext_arr),
            ]));
        }

        {
            $file_type = 1;
            if (!empty(request()->param('file_type'))) {
                $file_type = request()->param('file_type');
            }

            $path = $this->fileSave($file_type, $file);
        }

        try {
            // 返回访问 URL（根据实际域名调整）
            $url = '/storage/' . $path;
            $file_size = $file->getSize();

            if ($file_size > 1024 * 1024 * 10) {
                exit(json_encode([
                    'code'    => 10005,
                    'message' => '上传失败，图片不能大于10M',
                ]));
            }

            // 图片大于2M压缩
            if ($file_size > 1024 * 1024 * 1) {
                $url_arr = explode('.', $url);
                $url_to = $url_arr[0] . "_" . rand(100, 999) . "." . $file->extension();

                $url = imageThumb(substr($url, 1), substr($url_to, 1), $file->extension());
            }

            return CatchResponse::success([
                'url'     => $url,
                'web_url' => request()->domain() . $url,
                'size'    => $file_size,
            ]);
        } catch (\Exception $e) {
            exit(json_encode([
                'code'    => 10005,
                'message' => '上传失败',
            ]));
        }
    }

}
